// Get the "extensions.jaikool.pref." branch
const JK_PREFERENCE_BRANCH = "extensions.jaikool.pref.";

var _gel = function(id, node) {
	if ("undefined" == typeof node || !node || !node.getElementById) {
		node = document;
	}
	return node.getElementById(id);
}
var Logger = function(loggername, level, prefsBranch) {
	const LEVEL_ALL = -999;
	const LEVEL_DEBUG = 0;
	const LEVEL_INFO = 1;
	const LEVEL_WARN = 2;
	const LEVEL_ERROR = 3;
	const LEVEL_FATAL = 4;
	const LEVEL_NONE = 999;
	var prefsService = Components.classes["@mozilla.org/preferences-service;1"]
			.getService(Components.interfaces.nsIPrefService);
	var consoleService = Components.classes["@mozilla.org/consoleservice;1"]
			.getService(Components.interfaces.nsIConsoleService);
	var nsIScriptError = Components.interfaces.nsIScriptError;
	var prefs = prefsService.getBranch(prefsBranch);

	var myname = loggername ? loggername : "DefaultLogger";
	this.logLevel = LEVEL_INFO;
	this.configure = function(lvl) {
		if (lvl) {
			this.logLevel = lvl;
		} else if (prefsBranch) {
			try {
				this.logLevel = prefs.getIntPref("loglevel." + myname);
			} catch (err) {
				// ignore pref not found
				try {
					this.logLevel = prefs.getIntPref("loglevel");
				} catch (err2){
					this.logLevel = LEVEL_INFO;
				}
			}
		}
	};
	this.configure(level);
	this.debug = function(aMessage) {
		if (this.logLevel > LEVEL_DEBUG)
			return;
		consoleService.logStringMessage(myname + " [DEBUG]:" + aMessage);
	};
	this.info = function(aMessage) {
		if (this.logLevel > LEVEL_INFO)
			return;
		consoleService.logStringMessage(myname + " [INFO]:" + aMessage);
	};
	this.warn = function(aMessage, err) {
		if (this.logLevel > LEVEL_WARN)
			return;
		var msg = myname + " [WARN]:" + aMessage;
		logMessage(msg, err, nsIScriptError.warningFlag);
	};
	this.error = function(aMessage, err) {
		if (this.logLevel > LEVEL_ERROR)
			return;
		var msg = myname + " [ERROR]:" + aMessage;
		logMessage(msg, err, nsIScriptError.errorFlag);
	};
	this.fatal = function(aMessage, err) {
		if (this.logLevel > LEVEL_FATAL)
			return;
		var msg = myname + " [FATAL]:" + aMessage;
		logMessage(msg, err, nsIScriptError.exceptionFlag);
	};
	function logMessage(aMessage, err, flag) {
		if (err) {
			var scriptError = Components.classes['@mozilla.org/scripterror;1']
					.createInstance(Components.interfaces.nsIScriptError);
			scriptError.init(msg + ", reason: " + err.message, err.sourceName,
					err.sourceLine, err.lineNumber, err.columnNumber, flag,
					null);
			consoleService.logMessage(scriptError);
		} else {
			consoleService.logStringMessage(msg);
		}
	}
}

var jk_logger = new Logger("jaikool", null, JK_PREFERENCE_BRANCH);

function isDef(ref) {
	return 'undefined' != typeof ref;
}